﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Edit_Form
{
    public partial class ICM_Pre_Purchase_Request_Urgent : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        IBLLPrePurchaseRequest bll = new PrePurchaseRequestBLL();
        IBLLPrePurchaseRequestItem bllPprItem = new PrePurchaseRequestItemBLL();
        IBLLPrePurchaseRequestCommittee bllPprCommittee = new PrePurchaseRequestCommitteeBLL();
        IBLLDocument bllPprFile = new DocumentBLL();
        IBLLTree bllTree = new TreeBLL();
        IBLLMasterPurchaseType bllPurchaseType = new MasterPurchaseTypeBLL();
        IBLLMasterPurchaseMapping bllPurchaseMap = new MasterPurchaseMappingBLL();
        IBLLSysPprPriority bllPprPriority = new SysPprPriorityBLL();
        IBLLSysPprType bllPprType = new SysPprTypeBLL();
        IBLLSysPprMethod bllPprMethod = new SysPprMethodBLL();
        IBLLBgmSource bllSource = new BgmSourceBLL();
        IBLLResourceMasterItem bllItem = new ResourceMasterItemBLL();
        IBLLBgmRequestExpense bllReqExpense = new BgmRequestExpenseBLL();
        IBLLMasterCommitteeFunction bllComFunction = new MasterCommitteeFunctionBLL();
        IBLLMasterCommitteePosition bllComPosition = new MasterCommitteePositionBLL();
        IBLLMasterCommitteeMapping bllComMapping = new MasterCommitteeMappingBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();
        IBLLSysDurationCount bllDurationCount = new SysDurationCountBLL();
        IBLLBgmProjectOperation bllOperation = new BgmProjectOperationBLL();
        IBLLSysDurationType bllDurationType = new SysDurationTypeBLL();
        IBLLBgmProjectExpense bllProjectExpense = new BgmProjectExpenseBLL();
        IBLLBgmProjectOperationExpense bllOperationExpense = new BgmProjectOperationExpenseBLL();
        double sumValue = 0;
        double totalPrice = 0;
        int nCount = 0;
        private const int ItemsPerRequest = 10;
        IBLLSysYearType bllYearType = new SysYearTypeBLL();
        IBLLBgmProjectExpense bllProExpense = new BgmProjectExpenseBLL();
        IBLLMasterPurchaseRule bllRule = new MasterPurchaseRuleBLL();
        PrePurchaseRequestRejectBLL bllPprReject = new PrePurchaseRequestRejectBLL();
        List<string[]> ApproveControlName = new List<string[]>();
        List<string> DelButtonApproveName = new List<string>();
        List<string[]> KnowControlName = new List<string[]>();
        List<string> DelButtonKnowName = new List<string>();
        List<PrePurchaseRequestRouteInfo> InfoPprRoute = new List<PrePurchaseRequestRouteInfo>();
        IBLLBgmProject bllProject = new BgmProjectBLL();
        SysUseMethodBLL bllUseMethod = new SysUseMethodBLL();
        HrmJobSiteBLL bllJobSite = new HrmJobSiteBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadPurchaseType();
                //LoadJobSiteTree(); // Amp Method
                LoadYearType(); // Amp Method
                //LoadProjectTree();
                //LoadOperationTree();
                //LoadRootNodes(TreeItem, TreeNodeExpandMode.ServerSideCallBack);
                GetKeyValue();
                TipConfirm.TargetControls.Add(btnConfirm.ClientID, true);
            }
        }

        protected void cbJobSite_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmJobSiteInfo> infoList = bllJobSite.GetJobSite(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbJobSite.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdScopeName = new TableCell();
                Label lblScopeName = new Label();
                lblScopeName.Text = infoList[i].InfoScope.Name;
                tdScopeName.Width = Unit.Pixel(100);
                tdScopeName.Controls.Add(lblScopeName);
                tr.Cells.Add(tdScopeName);

                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].Name;
                tdJobSite.Width = Unit.Pixel(500);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);

                ((Table)cbJobSite.Items[j].FindControl("tableJobSite")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        protected void SetHistoryButton(PrePurchaseRequestInfo info)
        {
            Button TmpBtn = (Button)RadPanelBar1.FindItemByValue("Bar1").FindControl("btnHistoryApprove");
            this.TipHistoryApprove.TargetControls.Add(TmpBtn.ClientID, "HisApprove:" + info.Seq, true);

            TmpBtn = (Button)RadPanelBar1.FindItemByValue("Bar1").FindControl("btnHistoryInform");
            this.TipHistoryInform.TargetControls.Add(TmpBtn.ClientID, "HisInform:" + info.Seq, true);
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (RadTabStrip1.SelectedTab.Value == "Detail")
            {
                GetKeyValue();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Item")
            {
                LoadGridItem();
                string strJobSite = "";
                string strYear = "";
                if (ViewState["JobSite"] != null)
                {
                    strJobSite = ViewState["JobSite"].ToString();
                }
                if (ViewState["Year"] != null)
                {
                    strYear = ViewState["Year"].ToString();
                }
                if (cbJobSite.SelectedValue != strJobSite || txtYear.Text != strYear)
                {
                    LoadProjectTree();
                    LoadOperationTree();
                    SetViewStateJobSite(cbJobSite.SelectedValue);
                    SetViewStateYear(txtYear.Text);
                }
            }
            else if (RadTabStrip1.SelectedTab.Value == "File")
            {
                LoadGridFile();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Progress")
            {
                RefreshProgress();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Reject")
            {
                LoadGrid_Reject();
            }
        }

        private void SetViewStateJobSite(string value)
        {
            ViewState["JobSite"] = value;
        }

        private void SetViewStateYear(string value)
        {
            ViewState["Year"] = value;
        }

        protected void RefreshDisplay()
        {
            RadManager1.ResponseScripts.Add(@"CloseActiveToolTip();");
            GetKeyValue();
        }

        protected int GetSeq()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            return seq;
        }

        protected void Alert()
        {
            RadManager1.Alert(Convert.ToString(Session["Alert"]));
        }

        protected void OnAjaxUpdateConfirm(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTipConfirm(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTipConfirm(string elementID, UpdatePanel panel)
        {
            Control ctrl = Page.LoadControl("../UserControl/TIP_Pre_Purchase_Request_Confirm.ascx");
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Pre_Purchase_Request_Confirm)ctrl).RefreshParentDisplay = new CallBackHandle(RefreshDisplay);
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Pre_Purchase_Request_Confirm)ctrl).GetPprSeq = new CallBackHandleReturnInt(GetSeq);
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Pre_Purchase_Request_Confirm)ctrl).Alert = new CallBackHandleAlert(Alert);
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        public void GetKeyValue()
        {
            PrePurchaseRequestInfo info = new PrePurchaseRequestInfo();
            string day = "";
            string month = "";
            string year = "";
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            info = bll.GetPrePurchaseRequest(Convert.ToInt32(seq));
            hdUseMethod.Value = info.InfoPprUseMethod.Seq.ToString();
            lblHeaderYearType.Text = info.InfoYearType.Name;
            lblHeaderBgmYear.Text = info.Year.ToString();
            lblHeaderJobSite.Text = info.InfoJobSiteRequest.Name;
            lblStatus.Text = info.InfoRecord.InfoStatus.Name;
            string[] all_date = info.DateRequested.ToString().Split('/');
            if (all_date[0].Length > 0)
            {
                if (all_date[0].Length < 2)
                {
                    day = "0" + all_date[0];
                }
                else
                {
                    day = all_date[0];
                }
                if (all_date[1].Length < 2)
                {
                    month = "0" + all_date[1];
                }
                else
                {
                    month = all_date[1];
                }

                year = all_date[2];
                txtDate.Text = day + "/" + month + "/" + year;
            }
            cbPurchaseType.SelectedValue = info.InfoPurchaseType.Seq.ToString();
            cbPurchaseType.Enabled = false;
            txtName.Text = info.Name;
            txtReason.Text = info.Reason;
            //SettingSelectJobSiteTree(info);// Amp Method
            cbJobSite.SelectedValue = info.InfoJobSiteRequest.Seq.ToString();
            cbJobSite.Text = info.InfoJobSiteRequest.Name;

            cbYearType.SelectedValue = info.InfoYearType.Seq.ToString();
            txtYear.Text = info.Year.ToString();

            ManageDisplay(info);
            SetHistoryButton(info);
            cmdFac.ViewCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
        }

        private void InputItem(string seq, string name, string unit_name)
        {
            IList<PrePurchaseRequestItemInfo> infoListAddPprItem = new List<PrePurchaseRequestItemInfo>();
            BgmExpenseInfo infoExpense = new BgmExpenseInfo();
            BgmSourceInfo infoSource = new BgmSourceInfo();
            ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
            MasterUnitInfo infoUnit = new MasterUnitInfo();
            PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
            MasterPurchaseRuleInfo infoRule = new MasterPurchaseRuleInfo();
            BgmProjectExpenseInfo infoProjectExpense = new BgmProjectExpenseInfo();
            BgmProjectInfo infoProject = new BgmProjectInfo();
            BgmProjectOperationExpenseInfo infoOperationExpense = new BgmProjectOperationExpenseInfo();
            BgmProjectOperationInfo infoOperation = new BgmProjectOperationInfo();
            string[] all_value = seq.Split(new string[] { "-" }, StringSplitOptions.None);
            string[] all_name = name.Split(new string[] { " - " }, StringSplitOptions.None);

            if (ViewState["AddPprItem"] != null)
            {
                infoListAddPprItem = (List<PrePurchaseRequestItemInfo>)ViewState["AddPprItem"];
                foreach (PrePurchaseRequestItemInfo info in infoListAddPprItem)
                {
                    if (info.InfoItem.Seq == Convert.ToInt32(all_value[3]))
                    {
                        return;
                    }
                }
            }
            infoPprItem.Name = all_name[1];
            infoItem.Seq = Convert.ToInt32(all_value[3]);
            infoUnit.Name = unit_name;
            infoSource.Seq = Convert.ToInt32(hdSourceSeq.Value);
            infoSource.Name = hdSourceName.Value;
            infoExpense.Seq = Convert.ToInt32(hdExpenseSeq.Value);
            infoExpense.Name = hdExpenseName.Value;
            if (hdOperationSeq.Value.Length > 0)
            {
                infoOperation.Seq = Convert.ToInt32(hdOperationSeq.Value);
                infoOperation.Name = hdOperationName.Value;
                infoOperationExpense.Seq = Convert.ToInt32(hdOperationExpSeq.Value.ToString());
                infoOperationExpense.InfoOperation = infoOperation;
            }
            else
            {
                infoProject.Seq = Convert.ToInt32(hdProjectSeq.Value);
                infoProject.Name = hdProjectName.Value;
                infoProjectExpense.Seq = Convert.ToInt32(hdProjectExpSeq.Value);
                infoProjectExpense.InfoProject = infoProject;
            }
            infoRule.Seq = Convert.ToInt32(hdRule.Value);
            infoRule.Name = hdRuleName.Value;
            infoItem.InfoUnit = infoUnit;
            infoPprItem.InfoItem = infoItem;
            infoPprItem.InfoSource = infoSource;
            infoPprItem.InfoExpense = infoExpense;
            infoPprItem.InfoProjectExpense = infoProjectExpense;
            infoPprItem.InfoOperationExpense = infoOperationExpense;
            infoPprItem.InfoRule = infoRule;
            infoListAddPprItem.Add(infoPprItem);
            ViewState["AddPprItem"] = infoListAddPprItem;
        }

        protected void LoadPurchaseType()
        {
            IList<MasterPurchaseTypeInfo> infoList = bllPurchaseType.GetMasterPurchaseType();
            cbPurchaseType.DataSource = infoList;
            cbPurchaseType.DataBind();
        }

        protected void LoadOperationTree()
        {
            IList<TreeInfo> info = bllTree.GetBgmExpenseProjectOperation(Convert.ToInt32(txtYear.Text), Convert.ToInt32(cbJobSite.SelectedValue));
            RadTreeView tree = (RadTreeView)cbOperation.Items[0].FindControl("TreeViewOperation");

            tree.DataSource = info;
            tree.DataBind();
        }

        protected void LoadProjectTree()
        {
            IList<TreeInfo> info = bllTree.GetBgmExpenseProject(Convert.ToInt32(txtYear.Text), Convert.ToInt32(cbJobSite.SelectedValue));
            RadTreeView tree = (RadTreeView)cbProject.Items[0].FindControl("TreeViewProject");

            tree.DataSource = info;
            tree.DataBind();
        }

        protected void LoadGridSubItem()
        {
            IList<PrePurchaseRequestItemInfo> infoListAddPprItem = new List<PrePurchaseRequestItemInfo>();
            if (ViewState["AddPprItem"] != null)
            {
                infoListAddPprItem = (List<PrePurchaseRequestItemInfo>)ViewState["AddPprItem"];
            }
            Grid_SubItem.DataSource = infoListAddPprItem;
            Grid_SubItem.DataBind();
        }

        protected void LoadGridItem()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            IList<PrePurchaseRequestItemInfo> infoList = bllPprItem.GetPrePurchaseRequestItemWithParent(seq);
            Grid_Item.DataSource = infoList;
            GridGroupByExpression geSource = new GridGroupByExpression(Grid_Item.Columns[1]);
            GridGroupByExpression geExpense = new GridGroupByExpression(Grid_Item.Columns[2]);
            GridGroupByExpression geRule = new GridGroupByExpression(Grid_Item.Columns[3]);
            GridGroupByExpression geProOper = new GridGroupByExpression(Grid_Item.Columns[4]);
            GridGroupByExpression geProject = new GridGroupByExpression(Grid_Item.Columns[5]);

            if (infoList.Count > 0)
            {
                Grid_Item.MasterTableView.GroupByExpressions.Add(geRule);
                //Grid_Item.MasterTableView.GroupByExpressions.Add(geSource);
                if (infoList[0].InfoOperationExpense.InfoOperation.Seq != null)
                {
                    Grid_Item.MasterTableView.GroupByExpressions.Add(geProOper);
                }
                if (infoList[0].InfoProjectExpense.InfoProject.Seq != null)
                {
                    Grid_Item.MasterTableView.GroupByExpressions.Add(geProject);
                }
                Grid_Item.MasterTableView.GroupByExpressions.Add(geExpense);
            }

            Grid_Item.DataBind();
            
            if (Grid_Item.Items.Count == 0)
            {
                ViewState["Rule"] = null;
            }
            else
            {
                hdRule.Value = bllPprItem.GetPrePurchaseRequestRule(seq);
            }

            cmdFac.GridCommand(panelList_Item, panelGrid_Item, panelCommand_Item);
        }

        protected void LoadGridFile()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            Grid_File.DataSource = bllPprFile.GetDocument(seq, "ICM_PRE_PURCHASE_REQUEST_FILE", "ICM_PPR_SEQ", "ICM_PPR_FILE_SEQ");
            Grid_File.DataBind();

            cmdFac.GridCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void TreeItem_NodeExpand(object sender, RadTreeNodeEventArgs e)
        {
            PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);
        }

        private static void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
        {
            IBLLTree bll = new TreeBLL();

            foreach (TreeInfo info in bll.GetResourceMasterTreeWithoutHeader(""))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                node.Checkable = false;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                treeView.Nodes.Add(node);
            }
        }

        private static void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        {
            e.Node.Dispose();
            e.Node.Nodes.Clear();
            IBLLTree bll = new TreeBLL();
            foreach (TreeInfo info in bll.GetResourceMasterTreeWithoutHeader(e.Node.Value))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                node.Checkable = (info.Category == "ITEM");
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                e.Node.Nodes.Add(node);
            }

            e.Node.Expanded = true;
            e.Node.ExpandMode = expandMode;
        }

        protected void btnSelectItem_Click(object sender, EventArgs e)
        {
            foreach (RadTreeNode node in TreeItem.GetAllNodes())
            {
                if (node.Checkable && node.Checked)
                {
                    InputItem(node.Value, node.Text, node.ToolTip);
                }
            }
            LoadGridSubItem();
        }

        protected void btnDeleteItem_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_SubItem.MasterTableView.GetSelectedItems().Length];
            int item = Grid_SubItem.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_SubItem.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<PrePurchaseRequestItemInfo>)ViewState["AddPprItem"]).RemoveAt(data_value[i]);
            }
            LoadGridSubItem();
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            IList<PrePurchaseRequestItemInfo> infoListAddPprItem = new List<PrePurchaseRequestItemInfo>();
            string[] all_value = e.Argument.Split(new string[] { " : " }, StringSplitOptions.None);
            if (all_value[0] == "Project")
            {
                ViewState["AddPprItem"] = null;
                string[] data_value = all_value[1].Split(new string[] { "-" }, StringSplitOptions.None);
                hdRule.Value = data_value[0];
                hdProjectSeq.Value = data_value[2];
                hdProjectExpSeq.Value = data_value[3];
                BgmProjectExpenseInfo infoProjectExpense = bllProjectExpense.GetBgmProjectExpense(Convert.ToInt32(data_value[3]));
                MasterPurchaseRuleInfo infoRule = bllRule.GetMasterPurchaseRule(Convert.ToInt32(data_value[0]));
                BgmProjectInfo infoProject = bllProject.GetBgmProject(Convert.ToInt32(data_value[2]));
                udPanelItem.Visible = true;
                lblAllBudget.Text = Convert.ToDouble(infoProjectExpense.Price).ToString("###,###,##0.00");
                lblRemainBudget.Text = Convert.ToDouble(infoProjectExpense.Price).ToString("###,###,##0.00");
                if (infoProjectExpense.InfoItem.Seq != null) //เป็นค่าครุภัณฑ์ ที่ดิน สิ่งก่อสร้าง
                {
                    panelAddItem.Visible = false;
                    Grid_SubItem.Columns[0].Visible = false;
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
                    infoSource.Seq = infoProjectExpense.InfoSource.Seq;
                    infoSource.Name = infoProjectExpense.InfoSource.Name;
                    infoPprItem.Name = infoProjectExpense.InfoItem.Name;
                    infoPprItem.Qty = infoProjectExpense.Qty;
                    infoPprItem.Price = infoProjectExpense.Price;
                    infoExpense.Seq = infoProjectExpense.InfoExpense.Seq;
                    infoExpense.Name = infoProjectExpense.InfoExpense.Name;
                    infoItem.Seq = infoProjectExpense.InfoItem.Seq;
                    infoUnit.Name = infoProjectExpense.InfoItem.InfoUnit.Name;
                    infoItem.InfoUnit = infoUnit;
                    infoPprItem.InfoItem = infoItem;
                    infoPprItem.InfoExpense = infoExpense;
                    infoPprItem.InfoSource = infoSource;
                    infoPprItem.InfoRule = infoRule;

                    infoPprItem.InfoProjectExpense = infoProjectExpense;

                    infoListAddPprItem.Add(infoPprItem);
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
                else if (infoProjectExpense.InfoExpense.Name.IndexOf("วัสดุ") > 0) // เป็นค่าวัสดุ
                {
                    hdSourceSeq.Value = infoProjectExpense.InfoSource.Seq.ToString();
                    hdSourceName.Value = infoProjectExpense.InfoSource.Name;
                    hdExpenseSeq.Value = infoProjectExpense.InfoExpense.Seq.ToString();
                    hdExpenseName.Value = infoProjectExpense.InfoExpense.Name;
                    hdRule.Value = infoRule.Seq.ToString();
                    hdRuleName.Value = infoRule.Name;
                    hdProjectSeq.Value = infoProject.Seq.ToString();
                    hdProjectName.Value = infoProject.Name;
                    panelAddItem.Visible = true;
                    Grid_SubItem.Columns[0].Visible = true;
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
                else //เป็นรายจ่ายอื่นๆ เช่น ค่าจ้างเหมาบริการ 
                {
                    panelAddItem.Visible = false;
                    Grid_SubItem.Columns[0].Visible = false;
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
                    infoSource.Seq = infoProjectExpense.InfoSource.Seq;
                    infoSource.Name = infoProjectExpense.InfoSource.Name;
                    infoPprItem.Name = infoProjectExpense.InfoExpense.Name;
                    infoPprItem.Qty = (infoProjectExpense.Qty.ToString().Length == 0 ? 1 : infoProjectExpense.Qty);
                    infoPprItem.Price = infoProjectExpense.Price;
                    infoExpense.Seq = infoProjectExpense.InfoExpense.Seq;
                    infoExpense.Name = infoProjectExpense.InfoExpense.Name;
                    infoUnit.Name = "รายการ";
                    infoItem.InfoUnit = infoUnit;
                    infoPprItem.InfoItem = infoItem;
                    infoPprItem.InfoExpense = infoExpense;
                    infoPprItem.InfoSource = infoSource;
                    infoPprItem.InfoRule = infoRule;

                    infoPprItem.InfoProjectExpense = infoProjectExpense;

                    infoListAddPprItem.Add(infoPprItem);
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
            }
            if (all_value[0] == "Operation")
            {
                ViewState["AddPprItem"] = null;
                string[] data_value = all_value[1].Split(new string[] { "-" }, StringSplitOptions.None);
                hdRule.Value = data_value[0];
                hdOperationSeq.Value = data_value[2];
                hdOperationExpSeq.Value = data_value[3];
                BgmProjectOperationExpenseInfo infoOperationExpense = bllOperationExpense.GetBgmProjectOperationExpense(Convert.ToInt32(data_value[3]));
                MasterPurchaseRuleInfo infoRule = bllRule.GetMasterPurchaseRule(Convert.ToInt32(data_value[0]));
                BgmProjectOperationInfo infoOperation = bllOperation.GetBgmProjectOperation(Convert.ToInt32(data_value[2]));
                udPanelItem.Visible = true;
                lblAllBudget.Text = Convert.ToDouble(infoOperationExpense.Price).ToString("###,###,##0.00");
                lblRemainBudget.Text = Convert.ToDouble(infoOperationExpense.Price).ToString("###,###,##0.00");
                if (infoOperationExpense.InfoItem.Seq != null) //เป็นค่าครุภัณฑ์ ที่ดิน สิ่งก่อสร้าง
                {
                    panelAddItem.Visible = false;
                    Grid_SubItem.Columns[0].Visible = false;
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
                    infoSource.Seq = infoOperationExpense.InfoSource.Seq;
                    infoSource.Name = infoOperationExpense.InfoSource.Name;
                    infoPprItem.Name = infoOperationExpense.InfoItem.Name;
                    infoPprItem.Qty = infoOperationExpense.Qty;
                    infoPprItem.Price = infoOperationExpense.Price;
                    infoExpense.Seq = infoOperationExpense.InfoExpense.Seq;
                    infoExpense.Name = infoOperationExpense.InfoExpense.Name;
                    infoItem.Seq = infoOperationExpense.InfoItem.Seq;
                    infoUnit.Name = infoOperationExpense.InfoItem.InfoUnit.Name;
                    infoItem.InfoUnit = infoUnit;
                    infoPprItem.InfoItem = infoItem;
                    infoPprItem.InfoExpense = infoExpense;
                    infoPprItem.InfoSource = infoSource;
                    infoPprItem.InfoRule = infoRule;

                    infoPprItem.InfoOperationExpense = infoOperationExpense;

                    infoListAddPprItem.Add(infoPprItem);
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
                else if (infoOperationExpense.InfoExpense.Name.IndexOf("วัสดุ") > 0) // เป็นค่าวัสดุ
                {
                    hdSourceSeq.Value = infoOperationExpense.InfoSource.Seq.ToString();
                    hdSourceName.Value = infoOperationExpense.InfoSource.Name;
                    hdExpenseSeq.Value = infoOperationExpense.InfoExpense.Seq.ToString();
                    hdExpenseName.Value = infoOperationExpense.InfoExpense.Name;
                    hdRule.Value = infoRule.Seq.ToString();
                    hdRuleName.Value = infoRule.Name;
                    hdOperationSeq.Value = infoOperation.Seq.ToString();
                    hdOperationName.Value = infoOperation.Name;
                    panelAddItem.Visible = true;
                    Grid_SubItem.Columns[0].Visible = true;
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
                else //เป็นรายจ่ายอื่นๆ เช่น ค่าจ้างเหมาบริการ 
                {
                    panelAddItem.Visible = false;
                    Grid_SubItem.Columns[0].Visible = false;
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
                    infoSource.Seq = infoOperationExpense.InfoSource.Seq;
                    infoSource.Name = infoOperationExpense.InfoSource.Name;
                    infoPprItem.Name = infoOperationExpense.InfoExpense.Name;
                    infoPprItem.Qty = (infoOperationExpense.Qty.ToString().Length == 0 ? 1 : infoOperationExpense.Qty); ;
                    infoPprItem.Price = infoOperationExpense.Price;
                    infoExpense.Seq = infoOperationExpense.InfoExpense.Seq;
                    infoExpense.Name = infoOperationExpense.InfoExpense.Name;
                    infoUnit.Name = "รายการ";
                    infoItem.InfoUnit = infoUnit;
                    infoPprItem.InfoItem = infoItem;
                    infoPprItem.InfoExpense = infoExpense;
                    infoPprItem.InfoSource = infoSource;
                    infoPprItem.InfoRule = infoRule;

                    infoPprItem.InfoOperationExpense = infoOperationExpense;

                    infoListAddPprItem.Add(infoPprItem);
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
            }

            LoadGridSubItem();

            foreach (GridDataItem data in Grid_SubItem.MasterTableView.Items)
            {
                ((RadNumericTextBox)data["Qty"].FindControl("txtQty")).Enabled = false;
            }
        }

        protected void Edit_Detail_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
            LoadValiDateDetail();
        }

        protected void EditSave_Detail_Click(object sender, EventArgs e)
        {
            PrePurchaseRequestInfo info = new PrePurchaseRequestInfo();
            SysYearTypeInfo infoYearType = new SysYearTypeInfo();
            HrmJobSiteInfo infoJobSiteRequest = new HrmJobSiteInfo();
            HrmJobSiteInfo infoJobSite = new HrmJobSiteInfo();
            HrmJobSiteInfo infoJobSiteDirect = new HrmJobSiteInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            MasterPurchaseTypeInfo infoPurchaseType = new MasterPurchaseTypeInfo();
            SysPprForInfo infoFor = new SysPprForInfo();
            SysDurationTypeInfo infoDurationType = new SysDurationTypeInfo();
            SysDurationCountInfo infoDurationCount = new SysDurationCountInfo();
            RecordInfo infoRecord = new RecordInfo();

            info.Seq = Convert.ToInt32(Request.QueryString["Seq"]);
            //RadTreeView JobSitetree = (RadTreeView)this.cbJobSite.Items[0].FindControl("TreeViewJobSite");
            //string[] seq = JobSitetree.SelectedValue.ToString().Split('-');
            infoJobSiteRequest.Seq = Convert.ToInt32(cbJobSite.SelectedValue);
            infoJobSite.Seq = Convert.ToInt32(cbJobSite.SelectedValue);
            infoJobSiteDirect.Seq = Convert.ToInt32(cbJobSite.SelectedValue);

            infoYearType.Seq = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            info.InfoYearType = infoYearType;
            info.Year = Convert.ToInt32(txtYear.Value);

            infoEmployee.Seq = 1;
            
            info.DateRequested = Convert.ToDateTime(txtDate.TextWithLiterals);
            infoPurchaseType.Seq = Convert.ToInt32(cbPurchaseType.SelectedValue);
            info.Name = txtName.Text;
            info.Reason = txtReason.Text;

            infoFor.Seq = null;

            info.DurationRequired = null;
            infoDurationType.Seq = null;
            infoDurationCount.Seq = null;

            info.DateRequired = null;

            infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Updated_when = DateTime.Now;
            info.InfoEmployeeRequest = infoEmployee;
            info.InfoPurchaseType = infoPurchaseType;
            info.InfoDurationCount = infoDurationCount;
            info.InfoDurationType = infoDurationType;
            info.InfoJobSite = infoJobSite;
            info.InfoJobSiteDirect = infoJobSiteDirect;
            info.InfoJobSiteRequest = infoJobSiteRequest;
            info.InfoRecord = infoRecord;
            info.InfoPprFor = infoFor;

            try
            {
                bll.Update(info);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            GetKeyValue();
        }

        protected void Cancel_Detail_Click(object sender, EventArgs e)
        {
            GetKeyValue();
        }

        protected void ShowGrid_Item_Click(object sender, EventArgs e)
        {
            cbProject.SelectedIndex = 0;
            cbOperation.SelectedIndex = 0;
            udPanelItem.Visible = false;
            ViewState["AddPprItem"] = null;
            LoadGridItem();
        }

        protected void AddNew_Item_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Item, panelGrid_Item, panelCommand_Item);
            LoadValiDateItem();
        }

        protected void AddNewSave_Item_Click(object sender, EventArgs e)
        {
            IList<PrePurchaseRequestItemInfo> infoListPprItem = new List<PrePurchaseRequestItemInfo>();
            IList<PrePurchaseRequestItemInfo> infoTempPprItem = new List<PrePurchaseRequestItemInfo>();
            if (Grid_SubItem.MasterTableView.Items.Count == 0)
            {
                RadManager1.Alert("กรุณาเลือกรายการพัสดุ");
                return;
            }
            else
            {
                if (ViewState["Rule"] != null)
                {
                    if (ViewState["Rule"].ToString() != hdRule.Value)
                    {
                        RadManager1.Alert("แผนการใช้จ่ายงบประมาณต้องอยู่ภายใต้ระเบียบการจัดหาเดียวกันเท่านั้น");
                        return;
                    }
                }

                foreach (GridDataItem data in Grid_SubItem.MasterTableView.Items)
                {
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    PrePurchaseRequestItemInfo info = new PrePurchaseRequestItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterPurchaseRuleInfo infoRule = new MasterPurchaseRuleInfo();
                    BgmProjectInfo infoProject = new BgmProjectInfo();
                    BgmProjectExpenseInfo infoProjectExpense = new BgmProjectExpenseInfo();
                    BgmProjectOperationInfo infoOperation = new BgmProjectOperationInfo();
                    BgmProjectOperationExpenseInfo infoOperationExpense = new BgmProjectOperationExpenseInfo();
                    RecordInfo infoRecord = new RecordInfo();
                    string item_seq = data["InfoItem.Seq"].Text;
                    string source_seq = data["InfoSource.Seq"].Text;
                    string source_name = data["InfoSource.Name"].Text;
                    string expense_seq = data["InfoExpense.Seq"].Text;
                    string expense_name = data["InfoExpense.Name"].Text;
                    string oper_seq = data["InfoOperationExpense.InfoOperation.Seq"].Text;
                    string oper_name = data["InfoOperationExpense.InfoOperation.Name"].Text;
                    string proj_seq = data["InfoProjectExpense.InfoProject.Seq"].Text;
                    string proj_name = data["InfoProjectExpense.InfoProject.Name"].Text;
                    string rule_seq = data["InfoRule.Seq"].Text;
                    string rule_name = data["InfoRule.Name"].Text;
                    string oper_exp_seq = data["InfoOperationExpense.seq"].Text;
                    string pro_exp_seq = data["InfoProjectExpense.seq"].Text;
                    string name = ((HyperLink)data["Name"].FindControl("lkName")).Text;
                    string descr = ((TextBox)data["Descr"].FindControl("txtDescr")).Text;
                    string qty = ((RadNumericTextBox)data["Qty"].FindControl("txtQty")).Value.ToString();
                    string price = ((RadNumericTextBox)data["Price"].FindControl("txtPrice")).Value.ToString();
                    string unit_name = data["InfoItem.InfoUnit.Name"].Text;
                    info.Name = name;
                    info.Descr = descr;
                    if (qty.Length == 0 || price.Length == 0)
                    {
                        RadManager1.Alert("กรุณาระบุจำนวนและราคาประมาณการต่อหน่วยให้ครบถ้วน");
                        return;
                    }
                    info.Qty = Convert.ToInt32(qty);
                    info.Price = Convert.ToDouble(price);
                    infoUnit.Name = unit_name;
                    if (item_seq.Replace("&nbsp;", "").Length > 0)
                    {
                        infoItem.Seq = Convert.ToInt32(item_seq);
                    }
                    infoExpense.Seq = Convert.ToInt32(expense_seq);
                    infoExpense.Name = expense_name;
                    infoSource.Seq = Convert.ToInt32(source_seq);
                    infoSource.Name = source_name;
                    infoRule.Seq = Convert.ToInt32(rule_seq);
                    infoRule.Name = rule_name;
                    infoRecord.Created_by = cn.UserID;
                    infoRecord.Created_when = DateTime.Now;
                    infoItem.InfoUnit = infoUnit;
                    info.InfoSource = infoSource;
                    info.InfoExpense = infoExpense;
                    info.InfoItem = infoItem;
                    info.InfoRecord = infoRecord;
                    info.InfoRule = infoRule;
                    if (proj_seq.Replace("&nbsp;", "").ToString().Length > 0)
                    {
                        infoProject.Seq = Convert.ToInt32(proj_seq);
                        infoProject.Name = proj_name.Replace("&nbsp;", "");
                        infoProjectExpense.Seq = Convert.ToInt32(pro_exp_seq.Replace("&nbsp;", ""));
                        infoProjectExpense.InfoProject = infoProject;
                        info.InfoProjectExpense = infoProjectExpense;
                    }
                    if (oper_seq.Replace("&nbsp;", "").ToString().Length > 0)
                    {
                        infoOperation.Seq = Convert.ToInt32(oper_seq);
                        infoOperation.Name = oper_name.Replace("&nbsp;", "");
                        infoOperationExpense.Seq = Convert.ToInt32(oper_exp_seq.Replace("&nbsp;", ""));
                        infoOperationExpense.InfoOperation = infoOperation;
                        info.InfoOperationExpense = infoOperationExpense;
                    }
                    infoTempPprItem.Add(info);
                }

                for (int i = 0; i < infoTempPprItem.Count; i++)
                {
                    infoListPprItem.Add(infoTempPprItem[i]);
                }

                try
                {
                    bllPprItem.Insert(infoListPprItem, Convert.ToInt32(Request.QueryString["Seq"]));
                    ViewState["Rule"] = hdRule.Value;
                    cbProject.SelectedIndex = 0;
                    cbOperation.SelectedIndex = 0;
                    udPanelItem.Visible = false;
                    TreeItem.ClearCheckedNodes();
                    LoadGridItem();
                }
                catch
                {
                    RadManager1.Alert(SystemInfo._InsertError);
                    return;
                }
            }
        }

        protected void Delete_Item_Click(object sender, EventArgs e)
        {
            IList<PrePurchaseRequestItemInfo> infoList = new List<PrePurchaseRequestItemInfo>();
            foreach (GridDataItem data in Grid_Item.MasterTableView.GetSelectedItems())
            {
                PrePurchaseRequestItemInfo info = new PrePurchaseRequestItemInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPprItem.DeleteFromDB(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridItem();
        }

        protected void ShowGrid_File_Click(object sender, EventArgs e)
        {
            LoadGridFile();
        }

        protected void AddNew_File_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_File, panelGrid_File, panelCommand_File);
            LoadValiDateFile();
        }

        protected void AddNewSave_File_Click(object sender, EventArgs e)
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            FileInfo infoFile = new FileInfo(hdSourceFile.Value);
            DocumentInfo info = new DocumentInfo();
            RecordInfo infoRecord = new RecordInfo();
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.File_info = infoFile;
            info.Name = txtFileName.Text;
            info.Dest_path = hdSourceFile.Value;
            info.InfoRecord = infoRecord;

            try
            {
                bllPprFile.InsertFileToDB(info, "ICM_PRE_PURCHASE_REQUEST_FILE", "ICM_PPR_SEQ", seq);
                LoadGridFile();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void Delete_File_Click(object sender, EventArgs e)
        {
            IList<DocumentInfo> infoList = new List<DocumentInfo>();
            foreach (GridDataItem data in Grid_File.MasterTableView.GetSelectedItems())
            {
                DocumentInfo info = new DocumentInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPprFile.DeleteFileFromDB(infoList, "ICM_PRE_PURCHASE_REQUEST_FILE", "ICM_PPR_FILE_SEQ");
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridFile();
        }

        protected void Grid_Item_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridItem();
        }

        protected void Grid_SubItem_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridSubItem();
        }

        protected void Grid_File_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridFile();
        }

        protected void OnAjaxUpdateItem(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTipItem(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTipItem(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            if (all_value[0] == "Item")
            {
                Session["Resource_Item_Id"] = all_value[1];
                Session["Expense_Id"] = null;
            }
            else
            {
                Session["Resource_Item_Id"] = null;
                Session["Expense_Id"] = all_value[1];
            }
            Control ctrl = Page.LoadControl("../UserControl/ICM_Pre_Purchase_Request.ascx");
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void OnAjaxUpdateItemDetail(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTipItemDetail(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTipItemDetail(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            Session["Resource_Item_Id"] = all_value[1];
            Control ctrl = Page.LoadControl("../UserControl/TIP_Item_Detail.ascx");
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void Grid_SubItem_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                double qty = 0;
                double price = 0;
                Control target = e.Item.FindControl("lkName");
                GridDataItem dataBoundItem = e.Item as GridDataItem;

                RadNumericTextBox txtPrice = ((RadNumericTextBox)(dataBoundItem["Price"].FindControl("txtPrice")));
                RadNumericTextBox txtQty = ((RadNumericTextBox)(dataBoundItem["Qty"].FindControl("txtQty")));

                txtPrice.Attributes.Add("onFocus", "return Focus('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");
                txtQty.Attributes.Add("onFocus", "return Focus('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");
                txtPrice.Attributes.Add("onBlur", "return Blur('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");
                txtQty.Attributes.Add("onBlur", "return Blur('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");

                if (((RadNumericTextBox)(dataBoundItem["Qty"].FindControl("txtQty"))).Value.ToString().Length > 0)
                {
                    qty = double.Parse(((RadNumericTextBox)(dataBoundItem["Qty"].FindControl("txtQty"))).Value.ToString());
                }
                if (((RadNumericTextBox)(dataBoundItem["Price"].FindControl("txtPrice"))).Value.ToString().Length > 0)
                {
                    price = double.Parse(((RadNumericTextBox)(dataBoundItem["Price"].FindControl("txtPrice"))).Value.ToString());
                }

                sumValue += (qty * price);
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipEachItem, null))
                    {
                        if (dataBoundItem["InfoItem.Seq"].Text.Length > 0 && dataBoundItem["InfoItem.Seq"].Text != "&nbsp;")
                        {
                            this.TipEachItem.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["InfoItem.Seq"].Text, true);
                        }
                        else
                        {
                            this.TipEachItem.TargetControls.Add(target.ClientID, "Expense:" + dataBoundItem["InfoExpense.Seq"].Text, true);
                        }
                    }
                }
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["Descr"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>วงเงินจัดหาทั้งหมด :</span> "));
                footer["Descr"].HorizontalAlign = HorizontalAlign.Right;
                ((RadNumericTextBox)footer["Price"].FindControl("txtTotalPrice")).Value = Double.Parse(sumValue.ToString());
            }
        }

        protected void Grid_Item_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (nCount == 0)
            {
                totalPrice = 0;
            }
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                nCount++;
                double qty = 0;
                double price = 0;
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");

                if (dataBoundItem["Qty"].Text.Length > 0)
                {
                    qty = double.Parse(dataBoundItem["Qty"].Text);
                }
                if (((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text.Length > 0)
                {
                    price = double.Parse(((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text);
                }

                totalPrice += (qty * price);

                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipItemDetail, null))
                    {
                        TipItemDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["InfoItem.Seq"].Text, true);
                    }
                }
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["Descr"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>วงเงินจัดหาทั้งหมด :</span> "));
                ((Label)footer["Price"].FindControl("lblTotalPrice")).Text = totalPrice.ToString("###,###,##0.00");
                nCount = 0;
            }
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        //---------------------------------------------------------------------------------

        #region ความคืบหน้า

        ProgressPrePurchaseRequestBLL bllPpr = new ProgressPrePurchaseRequestBLL();

        protected void LoadGridApprove()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            IList<PrePurchaseRequestRouteInfo> InfoPprRouteList = bllPpr.GetPrePurchaseRequestApprove(seq);
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar1").FindControl("GridApprove");
            TmpGrid.DataSource = InfoPprRouteList;
            TmpGrid.DataBind();
        }

        protected void LoadGridApproveHistory()
        {
            //IList<PrePurchaseRequestRouteHistoryInfo> InfoPprRouteHisList = bllPpr.GetPrePurchaseRequestApproveHistory((int)this.info.Seq);
            //RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar1").FindControl("GridHistory");
            //TmpGrid.DataSource = InfoPprRouteHisList;

            //GridGroupByExpression g;
            //TmpGrid.MasterTableView.GroupByExpressions.Clear();
            //g = new GridGroupByExpression(TmpGrid.Columns[0]);
            //TmpGrid.MasterTableView.GroupByExpressions.Add(g);

            //TmpGrid.Columns[0].Visible = false;
            //TmpGrid.DataBind();
        }

        protected void LoadGridInformHistory()
        {
            //IList<PrePurchaseRequestRouteHistoryInfo> InfoPprRouteHisList = bllPpr.GetPrePurchaseRequestInformHistory((int)this.info.Seq);
            //RadGrid TmpGrid2 = (RadGrid)RadPanelBar1.FindItemByValue("Bar1").FindControl("GridInformHis");
            //GridGroupByExpression g;
            //TmpGrid2.DataSource = InfoPprRouteHisList;
            //TmpGrid2.MasterTableView.GroupByExpressions.Clear();
            //g = new GridGroupByExpression(TmpGrid2.Columns[0]);
            //TmpGrid2.MasterTableView.GroupByExpressions.Add(g);

            //TmpGrid2.Columns[0].Visible = false;
            //TmpGrid2.DataBind();
        }

        protected void LoadGridInform()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            IList<PrePurchaseRequestRouteInfo> InfoPprRouteList = bllPpr.GetPrePurchaseRequestInform(seq);
            RadGrid TmpGrid2 = (RadGrid)RadPanelBar1.FindItemByValue("Bar1").FindControl("GridInform");
            GridGroupByExpression g;
            TmpGrid2.DataSource = InfoPprRouteList;
            TmpGrid2.MasterTableView.GroupByExpressions.Clear();
            g = new GridGroupByExpression(TmpGrid2.Columns[0]);
            TmpGrid2.MasterTableView.GroupByExpressions.Add(g);

            TmpGrid2.Columns[0].Visible = false;
            TmpGrid2.DataBind();
        }

        protected void LoadGridRequest()
        {
            IList<PrePurchaseRequestInfo> InfoPpr = bllPpr.GetPrePurchaseRequest(1);
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar2").FindControl("GridRequest");
            TmpGrid.DataSource = InfoPpr;
            TmpGrid.DataBind();
        }

        protected void LoadGridPublishing()
        {
            IList<BidInfo> InfoBid = bllPpr.GetBid(1);
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar3").FindControl("GridPublishing");
            TmpGrid.DataSource = InfoBid;
            TmpGrid.DataBind();
        }

        protected void GridApprove_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridApprove();
        }

        protected void GridHistory_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridApproveHistory();
        }

        protected void GridInformHis_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridInformHistory();
        }

        protected void GridInform_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridInform();
        }

        protected void GridRequest_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridRequest();
        }

        protected void GridRequest_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":prr", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":prr", true);
                    }
                }
            }
        }

        protected void GridPublishing_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridPublishing();
        }

        protected void GridPublishing_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":br", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":br", true);
                    }
                }
            }
        }

        protected void OnAjaxUpdate_AppDet(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_AppDet(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_AppDet(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            Session["RefNo"] = all_value[1];
            Session["DisType"] = all_value[2];
            Control ctrl = Page.LoadControl("../UserControl/TIP_Approve_Detail.ascx");
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void OnAjaxUpdate_HistoryApprove(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_HistoryApprove(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_HistoryApprove(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            Session["HisSeq"] = all_value[1];
            Control ctrl;
            if (all_value[0] == "HisApprove")
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryApprove.ascx");
            }
            else
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryInform.ascx");
            }
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void OnAjaxUpdate_HistoryInform(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_HistoryInform(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_HistoryInform(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            Session["HisSeq"] = all_value[1];
            Control ctrl;
            if (all_value[0] == "HisApprove")
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryApprove.ascx");
            }
            else
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryInform.ascx");
            }
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void btnHistoryApprove_Click(object sender, EventArgs e)
        {

        }

        protected void btnHistoryInform_Click(object sender, EventArgs e)
        {

        }

        protected void RefreshProgress()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);

            IBLLSysProgress bllProg = new SysProgressBLL();
            SysProgressInfo InfoProg = new SysProgressInfo();
            InfoProg = bllProg.GetSysProgress(seq);
            lblProgress.Text = InfoProg.Name;

            LoadGridApprove();
            LoadGridApproveHistory();
            LoadGridInformHistory();
            LoadGridInform();
            LoadGridRequest();
            LoadGridPublishing();
        }

        #endregion

        //---------------------------------------------------------------------------------

        #region ประวัติตีกลับ

        protected void LoadGrid_Reject()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            IList<PrePurchaseRequestRejectInfo> InfoPprReject = bllPprReject.GetHistoryReturned(seq);
            Grid_Reject.DataSource = InfoPprReject;
            Grid_Reject.DataBind();
        }

        protected void Grid_Reject_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGrid_Reject();
        }

        #endregion

        //---------------------------------------------------------------------------------

        #region Amp Function

        public void LoadJobSiteTree()
        {
            IList<TreeInfo> info = bllTree.GetJobSiteTree();
            RadTreeView tree = (RadTreeView)cbJobSite.Items[0].FindControl("TreeViewJobSite");

            tree.DataSource = info;
            tree.DataBind();
        }

        private void SettingSelectJobSiteTree(PrePurchaseRequestInfo info)
        {
            RadTreeView tree = (RadTreeView)cbJobSite.Items[0].FindControl("TreeViewJobSite");
            if (info.InfoJobSiteDirect.Seq.ToString().Length > 0)
            {
                RadTreeNode node = tree.FindNodeByValue(info.InfoJobSiteDirect.InfoScope.Seq.ToString() + "-" + info.InfoJobSiteDirect.Seq.ToString());
                node.Selected = true;
                if (tree.SelectedNode != null)
                {
                    cbJobSite.Text = tree.SelectedNode.Text;
                }
                else
                {
                    cbJobSite.Text = "";
                }
            }
        }

        protected void LoadYearType()
        {
            IList<SysYearTypeInfo> infoList = bllYearType.GetSysYearType();
            cbYearType.DataSource = infoList;
            cbYearType.DataBind();
        }

        protected void ManageDisplay(PrePurchaseRequestInfo info)
        {
            lblStatus.Text = info.InfoRecord.InfoStatus.Name;
            switch (info.InfoRecord.InfoStatus.Status)
            {
                case "A":
                case "P":
                    // tab ข้อมูลหลัก
                    panelCommand_Detail.Visible = false;
                    // tab รายการพัสดุ
                    panelCommand_Item.Visible = false;
                    // tab เอกสารแนบ
                    panelCommand_File.Visible = false;
                    btnConfirm.Visible = false;
                    btnDeny.Visible = true;
                    break;
                case "C":
                    // tab ข้อมูลหลัก
                    panelCommand_Detail.Visible = false;
                    // tab รายการพัสดุ
                    panelCommand_Item.Visible = false;
                    // tab เอกสารแนบ
                    panelCommand_File.Visible = false;
                    btnConfirm.Visible = false;
                    btnDeny.Visible = false;
                    break;
                case "N":
                case "R":
                case "W":
                    // tab ข้อมูลหลัก
                    panelCommand_Detail.Visible = true;
                    // tab รายการพัสดุ
                    panelCommand_Item.Visible = true;
                    // tab เอกสารแนบ
                    panelCommand_File.Visible = true;
                    btnConfirm.Visible = true;
                    btnDeny.Visible = false;
                    break;
            }
        }

        #endregion

        #region LoadValiDate

        private void LoadValiDateDetail()
        {
            RequiredFieldValidator valJobSite = new RequiredFieldValidator();
            valJobSite.ID = "ValcbJobSite";
            valJobSite.ControlToValidate = "cbJobSite";
            valJobSite.SetFocusOnError = true;
            valJobSite.Display = ValidatorDisplay.Dynamic;
            valJobSite.ErrorMessage = "* กรุณาระบุหน่วยงาน *";
            panelValJobSite.Controls.Add(valJobSite);
            RequiredFieldValidator valYearType = new RequiredFieldValidator();
            valYearType.ID = "ValcbYearType";
            valYearType.ControlToValidate = "cbYearType";
            valYearType.SetFocusOnError = true;
            valYearType.Display = ValidatorDisplay.Dynamic;
            valYearType.ErrorMessage = "* กรุณาระบุประเภทปี *";
            panelValYearType.Controls.Add(valYearType);
            RequiredFieldValidator valYear = new RequiredFieldValidator();
            valYear.ID = "ValtxtYear";
            valYear.ControlToValidate = "txtYear";
            valYear.SetFocusOnError = true;
            valYear.Display = ValidatorDisplay.Dynamic;
            valYear.ErrorMessage = "* กรุณาระบุปี *";
            panelValYear.Controls.Add(valYear);
            RequiredFieldValidator valPurchaseType = new RequiredFieldValidator();
            valPurchaseType.ID = "ValcbPurchaseType";
            valPurchaseType.ControlToValidate = "cbPurchaseType";
            valPurchaseType.SetFocusOnError = true;
            valPurchaseType.Display = ValidatorDisplay.Dynamic;
            valPurchaseType.ErrorMessage = "* กรุณาระบุประเภทการจัดหา *";
            panelValPurchaseType.Controls.Add(valPurchaseType);
            RequiredFieldValidator valDate = new RequiredFieldValidator();
            valDate.ID = "ValtxtDate";
            valDate.ControlToValidate = "txtDate";
            valDate.SetFocusOnError = true;
            valDate.Display = ValidatorDisplay.Dynamic;
            valDate.ErrorMessage = "* กรุณาระบุวันที่รายการ *";
            panelValDate.Controls.Add(valDate);
            CustomValidator valCustomDate = new CustomValidator();
            valCustomDate.ID = "ValCustomDate";
            valCustomDate.ControlToValidate = "txtDate";
            valCustomDate.SetFocusOnError = true;
            valCustomDate.Display = ValidatorDisplay.Dynamic;
            valCustomDate.ErrorMessage = "* กรุณาระบุวันที่ให้ถูกต้อง *";
            valCustomDate.ClientValidationFunction = "validateDate";
            panelValDate.Controls.Add(valCustomDate);
            RequiredFieldValidator valName = new RequiredFieldValidator();
            valName.ID = "ValtxtName";
            valName.ControlToValidate = "txtName";
            valName.SetFocusOnError = true;
            valName.Display = ValidatorDisplay.Dynamic;
            valName.ErrorMessage = "* กรุณาระบุเรื่อง *";
            panelValName.Controls.Add(valName);
        }

        private void LoadValiDateItem()
        {
            string UseMethod = hdUseMethod.Value;
            if (UseMethod == "1")
            {
                RequiredFieldValidator val = new RequiredFieldValidator();
                val.ID = "ValcbProject";
                val.ControlToValidate = "cbProject";
                val.SetFocusOnError = true;
                val.Display = ValidatorDisplay.Dynamic;
                val.ErrorMessage = "* กรุณาระบุรายจ่ายจากแผนการใช้จ่ายงบประมาณ *";
                panelValcbProject.Controls.Add(val);
                panelProject.Visible = true;
                panelOperation.Visible = false;
            }
            else if (UseMethod == "2")
            {
                RequiredFieldValidator valOperation = new RequiredFieldValidator();
                valOperation.ID = "ValcbOperation";
                valOperation.ControlToValidate = "cbOperation";
                valOperation.SetFocusOnError = true;
                valOperation.Display = ValidatorDisplay.Dynamic;
                valOperation.ErrorMessage = "* กรุณาระบุรายจ่ายจากอนุมัติหลักการ *";
                panelValcbOperation.Controls.Add(valOperation);
                panelProject.Visible = false;
                panelOperation.Visible = true;
            }
        }

        private void LoadValiDateFile()
        {
            RequiredFieldValidator valFileName = new RequiredFieldValidator();
            valFileName.ID = "ValtxtFileName";
            valFileName.ControlToValidate = "txtFileName";
            valFileName.SetFocusOnError = true;
            valFileName.Display = ValidatorDisplay.Dynamic;
            valFileName.ErrorMessage = "* กรุณาระบุชื่อไฟล์ *";
            panelValtxtFileName.Controls.Add(valFileName);
            RequiredFieldValidator valAttachment = new RequiredFieldValidator();
            valAttachment.ID = "Valattachment";
            valAttachment.ControlToValidate = "attachment";
            valAttachment.SetFocusOnError = true;
            valAttachment.Display = ValidatorDisplay.Dynamic;
            valAttachment.ErrorMessage = "* กรุณาระบุที่อยู่ไฟล์ *";
            panelValattachment.Controls.Add(valAttachment);
        }

        #endregion

        protected void clearFilter_Item_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid_Item.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid_Item.MasterTableView.FilterExpression = string.Empty;
            LoadGridItem();
        }

        protected void clearFilter_File_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid_File.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid_File.MasterTableView.FilterExpression = string.Empty;
            LoadGridFile();
        }
    }
}
